import 'dart:async';

import 'package:demo/app/widgets/line_horizontal.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../../../model/constant_model.dart';
import '../../../../model/person_model.dart';
import '../../../../net/api_provider.dart';
import '../../../../theme/app_colors.dart';
import '../../../../theme/app_text_theme.dart';

class AddBankController extends GetxController {


  var loanNum = ''; // 订单编号
  TextEditingController nameController = TextEditingController();
  TextEditingController bankController = TextEditingController();
  TextEditingController bankNumController = TextEditingController();
  TextEditingController phoneController = TextEditingController();
  TextEditingController codeController = TextEditingController();

  var codeBtnStr = '获取验证码'.obs;
  var canGetCode = true.obs; // 是否可以获取验证码
  Map<String, dynamic>? bankList; // 银行列表

  @override
  void onInit() {
    super.onInit();

    loanNum = Get.arguments['loan_num'];
  }

  @override
  void onReady() {
    super.onReady();

    getPersonDetail();
    getConstant();
  }

  /// 获取姓名和手机号
  void getPersonDetail() async{
    var detail = await apiProvider.getData({}, ApiProvider.person_detail);
    if(detail.code == 200){
      var person = Person.fromJson(detail.data);
      nameController.text = person.name;
      phoneController.text = person.phone;
    }
  }

  /// 获取银行卡列表
  void getConstant() async{
    var result = await apiProvider.getData({}, ApiProvider.constant);
    if(result.code == 200){
      var constant = Constant.fromJson(result.data);
      bankList = constant.bankList;
    }else{
      EasyLoading.showToast('${result.msg}');
    }
  }

  /// 选择银行卡
  void chooseBank(){
    if(bankList == null){
      getConstant();
      return;
    }

    Get.bottomSheet(
      Container(
        decoration: BoxDecoration(
          color: Color_white,
          borderRadius: BorderRadius.vertical(top: Radius.circular(8.w)),
        ),
        child: ListView.separated(
          shrinkWrap:true,
          padding: EdgeInsets.zero,
          itemCount: bankList?.length ?? 0,
          separatorBuilder: (BuildContext context, int index) => const LineHorizontal(),
          itemBuilder: (BuildContext context, int index) {
            var key = bankList?.keys.toList()[index];
            var value = bankList?.values.toList()[index];
            return InkWell(
              onTap: () => {
                bankController.text = value,
                Get.back()
              },
              child: Text('$value',style: text_131732_14).paddingOnly(left: 15.w,right: 15.w,top:12.w,bottom: 12.w),
            );
          },
        ),
      ),
    );
  }

  ApiProvider apiProvider = Get.find();
  void getCode() async {
    if(!canGetCode.value){
      return;
    }
    var phoneStr = phoneController.text;
    if(phoneStr.length != 11 || !phoneStr.startsWith('1')){
      EasyLoading.showToast('请输入正确的手机号');
    }else{
      Map<String, dynamic> obj = {'phone': phoneStr,};
      var result = await apiProvider.getData(obj,ApiProvider.login_code);
      if(result.code == 200){
        EasyLoading.showToast('验证码获取成功');
        startCountDown(60);
      }else{
        EasyLoading.showToast('验证码获取失败');
      }
    }
  }

  // 倒计时方法 time 倒计时时间
  void startCountDown(int time) {
    if(!canGetCode.value){
      return;
    }
    canGetCode.value = false;

    if (_timer != null) {
      killTimer();
    }
    if (time <= 0) {
      return;
    }

    var countTime = time;
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (countTime <= 0) {// 倒计时结束
        timer.cancel();
        codeBtnStr.value = '重新获取';
        canGetCode.value = true;
      } else {
        codeBtnStr.value = '${countTime}s';
        countTime--;
        canGetCode.value = false;
      }
    });
  }

  Timer? _timer; // 倒计时器
  void killTimer() {
    _timer?.cancel(); // 关闭计时器
    _timer = null; // 置空
  }


  @override
  void onClose() {
    super.onClose();
    killTimer();
  }

  /// 提交
  void submit(){
    var name = nameController.text;
    var bank = bankController.text;
    var bankNum = bankNumController.text;
    var phone = phoneController.text;
    var code = codeController.text;
    if(name.isEmpty){
      EasyLoading.showToast('请输入姓名');
      return;
    }
    if(bank.isEmpty){
      EasyLoading.showToast('请选择银行');
      return;
    }
    if(bankNum.isEmpty){
      EasyLoading.showToast('请填写银行卡号');
      return;
    }
    if(phone.length != 11 || !phone.startsWith('1')){
      EasyLoading.showToast('请填写正确的手机号');
      return;
    }
    if(code.isEmpty){
      EasyLoading.showToast('请填写验证码');
      return;
    }

    EasyLoading.showToast('添加成功');
    Get.back();
  }
}
